package ch.uzh.ifi.seal.ssqa.metrics;

import ch.uzh.ifi.seal.ssqa.model.DiagramComponent;
import ch.uzh.ifi.seal.ssqa.storage.IStorage;
import ch.uzh.ifi.seal.ssqa.storage.StorageResult;
import ch.uzh.ifi.seal.ssqa.storage.TeneoHibernateStorage;

public class IssueCountMetric implements IMetric{

	private static final String identifier = "ERROR";
	private static final String description = "Error Count in Time Interval";
	
	private double result = 0;
	
	String fromDateString = null;
	String toDateString = null;
	
	String issueType = "Defect";
	
	private IStorage storage; 
	
	@Override
	public String getIdentifier() {
		return this.identifier;
	}

	@Override
	public String getDescription() {
		return this.description;
	}

	/**
	 * @see ch.uzh.ifi.seal.ssqa.metrics.IMetric#calculateResult(Object)
	 */
	@Override
	public IMetric calculateResult(Object object) {
		
		String from = (this.fromDateString != null && this.fromDateString.trim() != "") ? " AND time.submissiondate > '"+this.fromDateString+"' " : "";
		String to = (this.toDateString != null && this.toDateString.trim() != "") ? " AND time.submissiondate < '"+this.toDateString+"' " : "";
		
		
		this.storage = new TeneoHibernateStorage();
		if(object instanceof DiagramComponent){
			this.result = this.calculate((DiagramComponent)object, from, to);
		}
		return this;
	}
	
	private double calculate(DiagramComponent component, String from , String to){
		// It is important, that the 'timetracking' is named as 'time' because from and to are refering to this.
		StorageResult result =  storage.executeUniqueSQLQuery("SELECT count(*) "
				+ "FROM `ssqa`.`issue` as issue "
				+ "JOIN `ssqa`.`timetracking` as time on issue.timetracking_timetracking_e_id = time.e_id "
				+ "JOIN `ssqa`.`revision` as revision on issue.id = revision.ucmactivity_ucmactivity_e_id "
				+ "JOIN `ssqa`.`component` component on revision.filepath = component.projectpath "
				+ "WHERE component.dtype = 'Source' " + "AND issue.type = '"+this.issueType+"' " + from + to +" AND diagrammapping = '"+component.getIdentifier()+"'");
		
		Number loc = (Number) result.getResult();
		result.getSession().close();
		if(loc != null){
			Double resultValue = loc.doubleValue();
			return resultValue;
		} else {
			return 0;
		}
	}

	@Override
	public double getResult() {
		return this.result;
	}
	
	/**
	 * 
	 * @param fromDate --> must be of format yyyy/MM/dd or NULL
	 * @param toDate --> must be of format yyyy/MM/dd or NULL
	 */
	public void setTimeInterval(String fromDate, String toDate){
		this.fromDateString = fromDate.replace("/", "-");
		this.fromDateString = fromDate.replace("/", "-");
	}
	
	/**
	 * 
	 * @param issueType --> the requested type of Issues 
	 */
	public void setIssueType(String issueType){
		if(issueType != null && issueType.trim()!= ""){
			this.issueType = issueType;
		}
	}

}
